package com.wms.web.interceptor;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.wms.data.pojo.SystemUser;

/**
 * User Login Interceptor.
 * 
 * <table border="1" width="80%">
 * <tr>
 * <th>Version</th>
 * <th>Date</th>
 * <th>Role</th>
 * <th>Modified By</th>
 * <th>Details</th>
 * </tr>
 * <tr>
 * <td>%I%</td>
 * <td>2011/11/18</td>
 * <td>SD/PG</td>
 * <td>Evan</td>
 * <td>Created By</td>
 * </tr>
 * </table>
 * <p/>
 * 
 * <pre>
 *	User Login Interceptor.
 * </pre>
 *
 * @author Evan
 * @version 1.0
 * @since 1.5
 * 
 * SVN:
 * <ol>
 * 	<li>$Id$</li>
 * 	<li>$Rev$</li>
 * </ol>
 *
 */
@ParentPackage("psts")
@Namespace("/app")
public class AuthorityInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		Map<String, Object> sessionMap = ActionContext.getContext().getSession();
		
		Object sysUser = sessionMap.get(SystemUser.PROP_SESSION_CODE_USER);
		
		if (sysUser == null) {
			
			return ActionSupport.LOGIN;
		}
		else {
			
			String actionName = invocation.getInvocationContext().getName();
			
			if (actionName != null && StringUtils.indexOf(actionName, "@") > 0) {
				
				String AuthorityStr = StringUtils.split(actionName, "@")[0];
				
				Map<String, String> userUrlMap = (Map<String, String>) invocation.getInvocationContext().getSession().get(SystemUser.PROP_SESSION_CODE_USER);
				
				if (StringUtils.isBlank(userUrlMap.get(AuthorityStr))) {
					
					return ActionSupport.LOGIN;
				}
			}
			
			return invocation.invoke();
		}
	}
}